package com.fl.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fl.boot.common.constant.MessageConstant;
import com.fl.boot.common.context.BaseContext;
import com.fl.boot.common.exception.AccountExistedException;
import com.fl.boot.common.exception.AccountNotFoundException;
import com.fl.boot.common.exception.PasswordUpdateException;
import com.fl.boot.mapper.AdminMapper;
import com.fl.boot.pojo.dto.AdminDTO;
import com.fl.boot.pojo.dto.AdminLoginDTO;
import com.fl.boot.pojo.dto.AdminQueryDTO;
import com.fl.boot.pojo.dto.PasswordEditDTO;
import com.fl.boot.pojo.entity.Admin;
import com.fl.boot.pojo.vo.AdminSelectVo;
import com.fl.boot.service.AdminService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: FL
 * @create: 2024 2024/3/26 21:16
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    AdminMapper adminMapper ;

    /**
     * 管理员登录
     * @param adminLoginDTO
     * @return
     */
    @Override
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

//        根据用户名查询数据库中的数据
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Admin admin = adminMapper.selectOne(queryWrapper);

//        处理各种情况(用户名不存在、密码不正确、账号被锁定)
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

//        密码比对
//        对用户输入的密码进行md5加密，然后和数据库中的密码进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!admin.getPassword().equals(password)) {
            //密码不正确
            throw new AccountNotFoundException(MessageConstant.PASSWORD_ERROR);
        }

//账号被锁定
        if (admin.getStatus() == 0) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_LOCKED);
        }

//        设置当前登录用户的id
        BaseContext.setCurrentId(admin.getId());

        return admin;
    }

    /**
     * 管理员注册
     * @param adminDTO
     */
    @Override
    public void save(AdminDTO adminDTO) {
        String username = adminDTO.getUsername();
        String password = adminDTO.getPassword();
        //        处理各种情况：账号已存在、密码不一致、手机号已存在
        if (adminMapper.selectCount(new QueryWrapper<Admin>().eq("username", username)) > 0) {
            //账号已存在
            throw new AccountExistedException(MessageConstant.ACCOUNT_EXISTS);
        }
        Admin admin = Admin.builder()
                .name(adminDTO.getName())
                .username(username)
                .password(password)
                .phone(adminDTO.getPhone())
                .email(adminDTO.getEmail())
                .gender(adminDTO.getGender())
                .idNumber(adminDTO.getIdNumber())
                .status(1)
                .build();
        adminMapper.insert(admin);

    }

    /**
     * 管理员信息更新
     * @param adminDTO
     */
    @Override
    public void update(AdminDTO adminDTO) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO, admin);
        adminMapper.update(admin, new QueryWrapper<Admin>().eq("id", adminDTO.getId()));
    }

    /**
     * 启用/禁用管理员账号
     * @param id
     * @param status
     */
    @Override
    public void enable(Long id, Integer status) {
//        处理各种情况：账号不存在
        Admin admin = adminMapper.selectById(id);
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        adminMapper.update(null, new UpdateWrapper<Admin>().eq("id", id).set("status", status));
    }

    /**
     * 修改管理员角色
     * @param id
     * @param role
     */
    @Override
    public void editRole(Long id, Integer role) {
//        处理各种情况：账号不存在
        Admin admin = adminMapper.selectById(id);
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        adminMapper.update(null, new UpdateWrapper<Admin>().eq("id", id).set("role", role));
    }

    /**
     * 查询管理员列表
     * @param adminQueryDTO
     * @return
     */
    @Override
    public List<AdminSelectVo> list(AdminQueryDTO adminQueryDTO) {
        List<Admin> adminList = adminMapper.selectAdmin(adminQueryDTO);
        List<AdminSelectVo> adminSelectVoList = new ArrayList<>();
        for (Admin admin : adminList) {
            AdminSelectVo adminSelectVo = new AdminSelectVo();
            BeanUtils.copyProperties(admin, adminSelectVo);
            adminSelectVoList.add(adminSelectVo);
        }
        return adminSelectVoList;
    }


    /**
     * 修改密码
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        Long id = passwordEditDTO.getId();
        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();
//        处理各种情况：账号不存在、旧密码与新密码一致
        if (adminMapper.selectCount(new QueryWrapper<Admin>().eq("id", id)) == 0) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
//        旧密码与新密码比对
        if (oldPassword.equals(newPassword)){
//            抛出密码修改失败异常
            throw new PasswordUpdateException(MessageConstant.PASSWORD_EQUAL);
        }
//        将新密码进行md5加密
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        adminMapper.update(null, new UpdateWrapper<Admin>().eq("id", id).set("password", newPassword));
    }




}
